import { LowCodeImp, ModelImp } from './type'
const lowCodeInstance = Symbol("lowCodeInstance");

type Unit = {
    key: string,
    label: string,
    desc: string,
    prefix: string,
    value: string | number | unknown,
    children?: Array<Unit>
}

export class Model implements ModelImp {
    private [lowCodeInstance]: LowCodeImp;
    modelTree: any;
    modelKeyList: { [key: string]: string }[] = [];
    constructor(lowcode: LowCodeImp,) {
        this[lowCodeInstance] = lowcode as LowCodeImp
        this.buildModelTree()
        this.buildModelKeyList()
        console.log('modelKeyList', this.modelKeyList)
    }

    buildModelTree() {
        let modelsList: never[] = []
        function deepTransition(map: { [key: string]: any }, list: Array<Unit>, parent: Unit | null) {
            if (Object.keys(map).length == 0) {
                return false
            }
            Object.entries(map).map(([key, value]) => {
                let unit: Unit = {
                    key: '',
                    label: key,
                    desc: key,
                    prefix: parent ? parent.prefix + '.' + key : key,
                    value: parent ? parent.prefix + '.' + key : key
                }
                list.push(unit)
                if (Object.prototype.toString.call(value) == '[object Object]') {
                    unit.children = []
                    deepTransition(value, unit.children, unit)
                }
            })
        }

        deepTransition(this[lowCodeInstance].model, modelsList, null)
        this.modelTree = modelsList
        // console.log('modelsList', modelsList)

    };

    buildModelKeyList() {
        this.modelKeyList = [];
        Object.entries(this[lowCodeInstance].model).map(item => {
            return this.modelKeyList.push({
                key: item[0],
                value: JSON.stringify(item[1], null, 2)
            });
        })
    }

    saveModel(key: string, model: any) {
        this[lowCodeInstance].model[key] = model;
        this[lowCodeInstance].modelController.buildModelTree();
        this[lowCodeInstance].modelController.buildModelKeyList();
    }

    selectModel(key: string): any {
        this[lowCodeInstance].modelController.buildModelTree();
        this[lowCodeInstance].modelController.buildModelKeyList();
        let model = this[lowCodeInstance].modelController.modelKeyList.find(
            (model) => key == model.key
        );
        return model
    }

    removeModel(key: string): void {
        delete this[lowCodeInstance].model[key];
        this[lowCodeInstance].modelController.buildModelTree();
        this[lowCodeInstance].modelController.buildModelKeyList();
    }
}